package com.yanx.common.security.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.yanx.common.enums.SystemError;
import com.yanx.common.enums.TokenError;
import com.yanx.common.exception.BusinessException;
import com.yanx.common.security.config.JwtProps;
import com.yanx.common.utils.Address_;
import com.yanx.common.utils.DateTime_;
import com.yanx.common.utils.Servlet_;
import com.yanx.common.utils.String_;
import com.yanx.framework.redis.RedisCache;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author gotanks
 */
@Component
@EnableConfigurationProperties(JwtProps.class)
public class TokenService {

    @Autowired
    private JwtProps jwtProps;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    /**
     * 登录用户 redis key
     */
    public static final String LOGIN_TOKEN_KEY = "login_tokens:";

    /**
     * 令牌前缀
     */
    public static final String TOKEN_PREFIX = "Bearer ";

    @Autowired
    private RedisCache redisCache;

    /**
     * 令牌前缀
     */
    public static final String LOGIN_USER_KEY = "login_user_key";

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser() {
        return getLoginUser(Servlet_.getRequest());
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (String_.isNotEmpty(token)) {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String uuid = claims.getAudience();
            if (uuid == null) {
                uuid = (String) claims.get(LOGIN_USER_KEY);
            }
            String userKey = getTokenKey(uuid);
            LoginUser user = redisCache.getCacheObject(userKey);
            return user;
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    private void setLoginUser(LoginUser loginUser) {
        if (loginUser != null && String_.isNotEmpty(loginUser.getUuid())) {
            UserAgent userAgent = UserAgentUtil.parse(Servlet_.getRequest().getHeader("User-Agent"));
            loginUser.setIpaddr(Servlet_.getClientIP(Servlet_.getRequest()));
            loginUser.setLoginLocation(Address_.getRealAddressByIP(loginUser.getIpaddr()));
            loginUser.setBrowser(userAgent.getBrowser().getName());
            loginUser.setOs(userAgent.getOs().getName());
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(HttpServletRequest request) {
        this.delLoginUser(getToken(request));
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token) {
        if (String_.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            redisCache.deleteObject(userKey);
        }
    }

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser) {
        String uuid = IdUtil.fastUUID();
        loginUser.setUuid(uuid);
        setLoginUser(loginUser);
        long nowMillis = DateTime_.current();
        //兼容ruoyi
        Map<String, Object> claims = new HashMap<>();
        claims.put(LOGIN_USER_KEY, uuid);
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                //uuid
                .setAudience(uuid)
                //兼容ruoyi
                .setClaims(claims)
                //用户名
                .setSubject(loginUser.getUsername())
                //签名密钥
                .signWith(SignatureAlgorithm.HS512, jwtProps.getSecret())
                // 添加Token签发时间
                .setIssuedAt(new Date(nowMillis))
//                .setExpiration(new Date(nowMillis + jwtProps.getExpireTime() * MILLIS_MINUTE))
                // 生成Token
                .compact();
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginUser 令牌
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = DateTime_.current();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(DateTime_.current());
        loginUser.setExpireTime(loginUser.getLoginTime() + jwtProps.getExpireTime() * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getUuid());
        redisCache.setCacheObject(userKey, loginUser, jwtProps.getExpireTime(), TimeUnit.MINUTES);
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(jwtProps.getSecret())
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException e) {
            throw new BusinessException(TokenError.E1001);
        } catch (SignatureException e) {
            throw new BusinessException(TokenError.E1002);
        } catch (UnsupportedJwtException e) {
            throw new BusinessException(TokenError.E1003);
        } catch (MalformedJwtException e) {
            throw new BusinessException(TokenError.E1004);
        } catch (IllegalArgumentException e) {
            throw new BusinessException(TokenError.E1005);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(SystemError.E999);
        }
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(jwtProps.getHeader());
        if (String_.isNotEmpty(token) && token.startsWith(TOKEN_PREFIX)) {
            token = token.replace(TOKEN_PREFIX, "");
        }
        return token;
    }

    /**
     * 获取username
     *
     * @param request
     * @return token
     */
    public String getUsername(HttpServletRequest request) {
        return getUsername(getToken(request));
    }

    /**
     * 获取username
     *
     * @param token
     * @return token
     */
    public String getUsername(String token) {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    private String getTokenKey(String uuid) {
        return LOGIN_TOKEN_KEY + uuid;
    }
}
